package org.example.business.endpoint.http.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import lombok.extern.slf4j.Slf4j;
import org.example.business.endpoint.http.event.message.HttpMsg;
import org.example.business.endpoint.http.event.message.HttpRsp;

@Slf4j
public class HttpMsgEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        log.info("编码消息 {}", msg);

        if(!(msg instanceof HttpMsg)){
            super.write(ctx, msg, promise);
            return;

        }

        ctx.writeAndFlush(transform2HttpResponse((HttpMsg)msg));

    }

    private DefaultFullHttpResponse transform2HttpResponse(HttpMsg httpMsg){

        HttpRsp httpRsp = httpMsg.getHttpRsp();

        DefaultFullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        transportStatus(httpRsp, fullHttpResponse);
        transportHeaders(httpRsp, fullHttpResponse);
        transportBody(httpRsp, fullHttpResponse);

        return fullHttpResponse;

    }

    private void transportStatus(HttpRsp httpRsp, FullHttpResponse httpResponse){
        httpResponse.setStatus(HttpResponseStatus.valueOf(httpRsp.getStatus()));

    }

    private void transportHeaders(HttpRsp httpRsp, FullHttpResponse httpResponse){
        httpRsp.getHeaders().forEach((key, value)->{
            httpResponse.headers().add(key, value);

        });

    }

    private void transportBody(HttpRsp httpRsp, FullHttpResponse httpResponse){
        httpResponse.content().writeBytes(httpRsp.getBody());


    }

}
